<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Crypt;
use DB;

class UserController extends Controller
{
    // 中间键 判断是否登录
    public function __construct()
    {
        $this -> middleware('login');
    }

	// add添加用户方法
    public function add()
    {
    	return view('admin.user.add', ['title' => '用户管理']);
    }

    // insert添加用户方法
    public function insert(Request $request)
    {
        // 验证规则
        $this->validate($request, [
            'hd_name' => 'required|min:5|max:18',
            'hd_pass' => 'required',
            'hd_repass' => 'same:hd_pass',
            'hd_sex' => 'required',
            'hd_phone' => 'digits:11',
            'hd_email' => 'email',
            'hd_pic' => 'image|max:2048',
        ],[
            // 自定位错误信息
            'hd_name.required' => '用户名不能为空!',
            'hd_name.min' => '用户名不能少于5位!',
            'hd_name.max' => '用户名不能大于18位!',
            'hd_pass.required' => '密码不能为空!',
            'hd_repass.same' => '两次密码不一致,请检查!',
            'hd_sex.required' => '请你输入性别',
            'hd_phone.digits' => '请输入11位正确手机号!',
            'hd_email.email' => '请输入正确邮箱格式!',
            'dh_pic.max' => '最大2M',
        ]);
        // dd($data);
        $data = $request -> except('_token', 'hd_repass');
        // dd($data);
        $userData['hd_name'] = $data['hd_name'];
        // 处理密码字段
        $userData['hd_pass'] = Crypt::encryptString($data['hd_pass']);
        $userData['hd_sex'] = $data['hd_sex'];
        $userData['hd_email'] = $data['hd_email'];
        // $userData['hd_pic'] = $data['hd_pic'];
        $userData['hd_phone'] = $data['hd_phone'];
        $userData['hd_status'] = $data['hd_status'];
        //处理头像
        if($request -> hasFile('hd_pic'))
        {
            if($request -> file('hd_pic') -> isValid())
            {
                $extension = $request -> file('hd_pic') -> getClientOriginalExtension();
                // echo $extension; 上一步获取图片后缀  方便后面拼接
                $filename = mt_rand(100000000, 999999999).'.'.$extension;
                $dir = './uploads/avatar/';
                $request -> file('hd_pic') -> move($dir, $filename);
                $userInfoData['hd_pic'] = '/uploads/avatar/'.$filename;
            }
        }else{
            $userInfoData['hd_pic'] = '/uploads/avatar/default.jpg';
        }
        $userData['hd_token'] = str_random(50);
        // 处理生成,更新时间
        $time = Date('Y-m-d H:i:s');
        $userData['created_at'] = $time;
        $userData['updated_at'] = $time;

        //添加数据
        $usersId = DB::table('users') -> insertGetId($userData);
        if($usersId)
        {
            $userInfoData['user_id']= $usersId;
            $userInfoData['created_at']= $time;
            $userInfoData['updated_at']= $time;

            $res = DB::table('user_info') -> insert($userInfoData);
            if($res)
            {
                return redirect('/Admin/user/index') -> with(['info' => '添加成功']);
            }else{
                return back() -> with(['info' => '添加失败']);
            }
        }
    }

    //index方法   用户详情页
    public function index(Request $request)
    {
        $num = $request -> input('num',5);
        $keywords = $request -> input('keywords','');
        // dd($userData);
        $data = DB::table('users')
            // -> select('users.*', 'user_info.hd_pic','user_info.id as uid')
            -> leftJoin('user_info', 'users.id', '=' ,'user_info.user_id')
            -> where('hd_name', 'like', '%'.$keywords.'%')
            -> paginate($num);
//         dd($data);
        return view('admin.user.index', ['data' => $data, 'request' => $request -> all(), 'title' => '用户列表']);
    }

    // ajax 双击修改用户名
    public function changename(Request $request)
    {
        // 获取传递过来的修改数据
        $id = $request -> id;
        $name = $request -> hd_name;

        // 添加到数据库中
        $res = DB::table('users') -> where('id',$id) -> update(['hd_name' => $name]);
        // 判断是否成功. 成功返回一.用来在模板中判断
        if($res)
        {
            return 1;
        }else{
            return 0;
        }
    }

    // edit 编辑修改用户
    public function edit($id)
    {
        $data = DB::table('users')
            -> select('users.*', 'user_info.hd_pic','user_info.signature')
            -> leftJoin('user_info', 'users.id', '=' ,'user_info.id')
            -> where('users.id', '=', $id)
            -> first();
        return view("Admin.user.edit", ['title' => '用户编辑', 'data' => $data]);
    }

    // update 更新edit提交过来的数据
    public function update(Request $request)
    {
        $this->validate($request, [
            'hd_name' => 'required|min:5|max:18',
            'hd_sex' => 'required',
            'hd_phone' => 'digits:11',
            'hd_email' => 'email',
            'hd_pic' => 'image|max:2048',
        ],[
            // 自定位错误信息
            'hd_name.required' => '用户名不能为空!',
            'hd_name.min' => '用户名不能少于5位!',
            'hd_name.max' => '用户名不能大于18位!',
            'hd_sex.required' => '请你输入性别',
            'hd_phone.digits' => '请输入11位正确手机号!',
            'hd_email.email' => '请输入正确邮箱格式!',
            'dh_pic.max' => '最大2M',
        ]);
        $id = $request -> id;
        $data = $request -> except('_token' ,'id' ,'hd_pic','signature');


        // 修改头像
        if($request -> hasFile('hd_pic'))
        {
            if($request -> file('hd_pic') -> isValid())
            {
                $extension = $request -> file('hd_pic') -> getClientOriginalExtension();
                // echo $extension; 上一步获取图片后缀  方便后面拼接
                $filename = mt_rand(100000000, 999999999).'.'.$extension;
                $dir = './uploads/avatar/';
                $request -> file('hd_pic') -> move($dir, $filename);
                $userInfoData['hd_pic'] = '/uploads/avatar/'.$filename;
                // signature插入个性签名到info表
// 是否正确????
                $userInfoData['signature'] = $request -> input('signature');
                // dd($userInfoData);
                // 获取原来图片地址  在删除
                $oldPic = DB::table('user_info') -> where('user_id',$id) -> first() -> hd_pic;
                // 判断 是否默认图片  不是就删除
                if(!empty($oldPic))
                {
                    if($oldPic != '/uploads/avatar/default.jpg')
                    {
                        if(file_exists('.'.$oldPic))
                        {
                            unlink('.'.$oldPic);
                        }
                    }
                }

                DB::table('user_info') -> where('user_id', $id) -> update($userInfoData);
            }
        }else{
            $userInfoData['hd_pic'] = '/uploads/avatar/default.jpg';
        }

        // 修改
        $res = DB::table('users') -> where('id', $id) -> update($data);
        if($res)
        {
            return redirect('/Admin/user/index') -> with(['info' => '修改成功']);
        }else
        {
            return back() -> with(['info' => '修改失败']);
        }
    }

    // delete 删除方法  还有联查图片
    public function delete($id)
    {
        $hd_pic = DB::table('user_info') -> where('id',$id) -> first() -> hd_pic;

        $res = DB::table('users') -> where('id',$id) -> delete();

        if($res)
        {
            DB::table('user_info') -> where('id', $id) -> delete();

            // 判断 是否默认图片  不是就删除
            if(!empty($oldPic))
            {
                if($oldPic != '/uploads/avatar/default.jpg')
                {
                    if(file_exists('.'.$oldPic))
                    {
                        unlink('.'.$oldPic);
                    }
                }
            }
        }

        if($res)
        {
            return redirect('/Admin/user/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }

    // 批量删除用户
    public function udelete(Request $request)
    {
        // dd($request -> all());
        $num = $request -> input('num',5);
        $keywords = $request -> input('keywords','');
        // dd($userData);
        $data = DB::table('users')
            -> select('users.*', 'user_info.hd_pic','user_info.id as uid')
            -> leftJoin('user_info', 'users.id', '=' ,'user_info.user_id')
            -> where('hd_name', 'like', '%'.$keywords.'%')
            -> paginate($num);
//         dd($data);
        return view('admin.user.udelete', ['data' => $data, 'request' => $request -> all(), 'title' => '批量删除用户']);
    }

    // 处理批量提交过来的
    public function piliang(Request $request)
    {
        $data = $request -> except('_token', 'num','keywords');
        // dd($data);


        $res = DB::table('users') -> whereIn('id', $data['id']) -> delete();

        if($res)
        {
            DB::table('user_info') -> whereIn('id', $data['id']) -> delete();

            // 判断 是否默认图片  不是就删除
            if(!empty($oldPic))
            {
                if($oldPic != '/uploads/avatar/default.jpg')
                {
                    if(file_exists('.'.$oldPic))
                    {
                        unlink('.'.$oldPic);
                    }
                }
            }
        }

        if($res)
        {
            return redirect('/Admin/user/index') -> with(['info' => '删除成功']);
        }else
        {
            return back() -> with(['info' => '删除失败']);
        }
    }

}
